package com.zyk.script.manager.holder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesHolder {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesHolder.class);

    private ClassLoader classLoader;

    public PropertiesHolder() {
        this(PropertiesHolder.class.getClassLoader());
    }

    public PropertiesHolder(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public Properties loadProperties() throws IOException {
        return loadProperties("script.properties");
    }

    public Properties loadProperties(String path) throws IOException {
        Properties properties = loadClassPathProperties(path);
        if (properties == null) {
            try {
                InputStream in = classLoader.getResourceAsStream("config/script.properties");
                properties = new Properties();
                properties.load(in);
            } catch (Exception ex) {
                logger.error("[ERROR] PropertiesHolder load error from file -> config/script.properties, meg:" + ex.toString());
            }
        }
        return properties;
    }

    private Properties loadClassPathProperties(String path) {
        try {
            InputStream in = classLoader.getResourceAsStream(path);
            Properties ps = new Properties();
            ps.load(in);
            return ps;
        } catch (Exception ex) {
            logger.error("[ERROR] PropertiesHolder load error from file -> script.properties, meg:" + ex.toString());
        }
        return null;
    }
}
